﻿import React, { Component } from 'react'
import PropTypes from 'prop-types'
import './Permission.css'
import permConverter from '../common/permConverter'
import Checkable from '../common/Checkable'
import lockIcon from '../imgs/lock.png'

export default class Permission extends Component {
    static propTypes = {
        teacher: PropTypes.shape({
            name: PropTypes.string.isRequired,
            perm: PropTypes.number,
            oldPerm: PropTypes.number
        }).isRequired,
        checkPerm: PropTypes.func.isRequired,
        submitChanges: PropTypes.func.isRequired,
        cancelChanges: PropTypes.func.isRequired
    }
    render() {
        var perms = permConverter.perm2arr(this.props.teacher.perm),
            powered = permConverter.hasGrantPerm(this.props.teacher.perm),
            permChanged = this.props.teacher.oldPerm !== undefined;
        return (
            <div className='perm-box'>
                <header>
                    {powered &&
                        <img alt='锁定' className='lock' src={lockIcon} />
                    }
                    {this.props.teacher.name}老师消息发送范围：
                    {permChanged &&
                        <span>
                            <button
                                className='btns'
                                onClick={this.props.submitChanges}>保存</button>
                            <button
                                className='btns'
                                onClick={this.props.cancelChanges}>放弃</button>
                        </span>
                    }
                </header>
                <div>
                    {perms.map((p, idx) =>
                        <Checkable
                            key={idx}
                            text={p.name}
                            disabled={powered}
                            checked={p.granted}
                            onCheck={() => this.props.checkPerm(idx)}
                        />
                    )}
                </div>
            </div>
        )
    }
}